package com.ruoyi.web.controller.delivery;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jianqiao.delivery.delivery.domain.DeliveryEntity;
import com.jianqiao.delivery.delivery.domain.ExpressPriceEntity;
import com.jianqiao.delivery.delivery.domain.TrajectoryEntity;
import com.jianqiao.delivery.delivery.service.DeliveryService;
import com.jianqiao.delivery.delivery.service.ExpressPriceService;
import com.jianqiao.delivery.delivery.service.TrajectoryService;
import com.jianqiao.delivery.expresscity.entity.ProvinceEntity;
import com.jianqiao.delivery.expresscity.service.ExpressService;
import com.jianqiao.delivery.jnttrack.entity.JntCreateEntity;
import com.jianqiao.delivery.jnttrack.entity.vo.JntTrackResponseVo;
import com.jianqiao.delivery.jnttrack.service.JntTrackService;
import com.jianqiao.delivery.seventeentrack.domain.RegisterParamVo;
import com.jianqiao.delivery.seventeentrack.service.SeventeenTrackService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.FieldUtil;
import com.ruoyi.common.utils.HttpClientUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * author: cyx
 * create: 2024/5/25 8:59
 **/
@RestController
@RequestMapping("/delivery")
@Slf4j
public class DeliveryController {

    @Autowired
    public DeliveryService deliveryService;

    @Autowired
    public ExpressPriceService expressPriceService;

    @Autowired
    public ExpressService expressService;

    @Autowired
    private TrajectoryService trajectoryService;

    @Autowired
    private JntTrackService jntTrackService;

    @Autowired
    private SeventeenTrackService seventeenTrackService;

    @Value("${expressUrl}")
    public String expressUrl;

    @Value("${philippinesUrl}")
    public String philippinesUrl;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * methood: 根据状态查对应状态的快递订单列表
     * auth: cyx
     * time: 2024/6/6 17:31
     **/
    @GetMapping("/selectDeliveryList")
    public AjaxResult selectDeliveryList(String statusCode, Integer pageSize, Integer pageNum) {
        if (StringUtils.isEmpty(statusCode)) {
            return AjaxResult.error("未传入订单状态值");
        }
        String uid = SecurityUtils.getUserId().toString();
        return AjaxResult.success(deliveryService.selectDeliver(statusCode, pageNum, pageSize, uid));
    }

    /**
     * methood: 新增海运快递订单
     * auth: cyx
     * time: 2024/6/6 17:31
     **/
    @PostMapping("/seaExpressInsert")
    public AjaxResult insertSeaExpressDelivery(@RequestBody DeliveryEntity[] deliveryEntities) {
        for (int i = 0; i < deliveryEntities.length; i++) {
            DeliveryEntity deliveryEntity = deliveryEntities[i];
            boolean fieldIsEmpty = FieldUtil.fieldIsEmpty("address,customsClearance,expressCompany,phone,productName," +
                    "realName,shippingChannel,trackingNumber,transportationMethod,unitPrice", deliveryEntity);
//            boolean fieldIsEmpty = FieldUtil.fieldIsEmpty("address,customsClearance,phone," +
//                    "realName,shippingChannel,transportationMethod", deliveryEntity);
            if (fieldIsEmpty) {
                return AjaxResult.error("存在未填的数据");
            }
            //校验货物价值是否为数字
            boolean checkNumber = FieldUtil.checkNumber(deliveryEntity.getUnitPrice());
            if (!checkNumber) {
                return AjaxResult.error("货物价值应填写数字");
            }
        }
        String uid = SecurityUtils.getUserId().toString();
        return AjaxResult.success(deliveryService.insertDelivery(deliveryEntities, uid));
    }

    /**
     * methood: 新增海运自送订单
     * auth: cyx
     * time: 2024/6/7 11:36
     **/
    @PostMapping("/seaSelfInsert")
    public AjaxResult insertSeaSelfDelivery(@RequestBody DeliveryEntity[] deliveryEntities) {
        for (int i = 0; i < deliveryEntities.length; i++) {
            DeliveryEntity deliveryEntity = deliveryEntities[i];
            boolean fieldIsEmpty = FieldUtil.fieldIsEmpty("address,customsClearance,destinationCountry,numberOfPieces,phone,plateNumber,productName," +
                    "realName,shippingChannel,transportationMethod,unitPrice", deliveryEntity);
            if (fieldIsEmpty) {
                return AjaxResult.error("存在未填的数据");
            }
        }
        String uid = SecurityUtils.getUserId().toString();
        return AjaxResult.success(deliveryService.insertDelivery(deliveryEntities, uid));
    }

    /**
     * methood: 新增空运快递订单
     * auth: cyx
     * time: 2024/6/7 11:36
     **/
    @PostMapping("/airInsert")
    public AjaxResult insertAirDelivery(@RequestBody DeliveryEntity[] deliveryEntities) {
        for (int i = 0; i < deliveryEntities.length; i++) {
            DeliveryEntity deliveryEntity = deliveryEntities[i];
            boolean fieldIsEmpty = FieldUtil.fieldIsEmpty("address,destinationCountry,numberOfPieces,phone,productName," +
                    "realName,trackingNumber,transportationMethod,unitPrice", deliveryEntity);
            if (fieldIsEmpty) {
                return AjaxResult.error("存在未填的数据");
            }
        }
        String uid = SecurityUtils.getUserId().toString();
        return AjaxResult.success(deliveryService.insertDelivery(deliveryEntities, uid));
    }

    @GetMapping("/countDelivery")
    public AjaxResult countDelivery() {
        String uid = SecurityUtils.getUserId().toString();
        return AjaxResult.success(deliveryService.countDelivery(uid));
    }

    /**
     * methood: 查看详情
     * auth: cyx
     * time: 2024/6/6 17:31
     **/
    @GetMapping("/detail")
    public AjaxResult selectDetail(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("未传入id");
        }
        DeliveryEntity delivery = deliveryService.selectDetail(id);
        return AjaxResult.success(delivery);
    }

    /**
     * methood: 取消订单
     * auth: cyx
     * time: 2024/6/6 17:30
     **/
    @PostMapping("/cancelDelivery")
    public AjaxResult cancelDelivery(@RequestBody Map<String, Object> paramMap) {
        String id = paramMap.get("id").toString();
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("未传入订单id");
        }
        int cancelCount = deliveryService.cancelDelivery(id);
        return AjaxResult.success(cancelCount);
    }

//    @PostMapping("/payOrder")
//    public AjaxResult payOrder(@RequestBody Map<String, String> paramMap) {
//        String id = paramMap.get("id");
//        if (StringUtils.isEmpty(id)) {
//            return AjaxResult.error("未传入订单id");
//        }
//        Long uid = LocalUser.getUser().getUid();
//        String result = deliveryService.payOrder(id, uid);
//        if ("0".equals(result)) {
//            return AjaxResult.error("支付失败");
//        }
//        return AjaxResult.success("支付成功");
//    }

    @GetMapping("/insertCity")
    public void insertCity() {
        deliveryService.insertCity();
    }

    @GetMapping("/getTrajectory")
    public AjaxResult getTrajectory(String jpNumber ,String DanHao, String ChannelID , HttpServletRequest request) throws IOException {
        //佐川/黑猫
        List<RegisterParamVo> numberList = new ArrayList<>();
        numberList.add(new RegisterParamVo(jpNumber));
        String registerNumber = seventeenTrackService.registerEvent(numberList);
        numberList.clear();
        numberList.add(new RegisterParamVo(registerNumber));
        String detailed = seventeenTrackService.detailEvent(numberList);


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("card", DanHao);
        Map<String, String> headMap = new HashMap<>();
        headMap.put("Accept", "application/json, text/javascript, */*; q=0.01");
        headMap.put("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36 Edg/126.0.0.0");
        String info = "";
        //日本轨迹查询
//        String substring = DanHao.substring(0, 2);
//        List<TrajectoryEntity> trajectoryList = new ArrayList<>();
//        String resultStr = "";
//        if ("JQ".equals(substring)){
//            trajectoryList = trajectoryService.listTrajectory(DanHao);
//            for (TrajectoryEntity trajectoryEntity : trajectoryList) {
//                Date arriveTime = trajectoryEntity.getArriveTime();
//                String arriveLocation = trajectoryEntity.getArriveLocation();
//                String context = trajectoryEntity.getContext();
//                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String arriveTimeStr = dateFormat.format(arriveTime);
//                resultStr = resultStr + arriveTimeStr + "   " + arriveLocation + "   " + context;
//                resultStr += "<br>";
//            }
//            int indexOf = resultStr.lastIndexOf("<");
//            info = resultStr.substring(0 ,indexOf);
//            info = "{ \"status\": 1,\"info\":\"" + info + "\",\"data\":null}";
//            return AjaxResult.success(info);
//        }
//        //印尼极兔轨迹查询
//        if ("JO".equals(substring)) {
//            List<JntTrackResponseVo> trackResponse = jntTrackService.jnttrack(DanHao);
//            for (JntTrackResponseVo responseVo : trackResponse) {
//                String dateTime = responseVo.getDate_time();
//                String cityName = responseVo.getCity_name();
//                String status = responseVo.getStatus();
//                resultStr = resultStr + dateTime + "   " + cityName + "   " + status;
//                resultStr += "<br>";
//            }
//            int indexOf = resultStr.lastIndexOf("<");
//            info = resultStr.substring(0 ,indexOf);
//            info = "{ \"status\": 1,\"info\":\"" + info + "\",\"data\":null}";
//            return AjaxResult.success(info);
//        }
        //菲律宾轨迹接口
        //中菲接口
        Map<String, Object> philippineMap = HttpClientUtil.doGet(philippinesUrl, paramMap, headMap);
        String resultMap= philippineMap.get("resultString").toString();
        // 使用 Jackson 的 ObjectMapper 将 JSON 字符串转换为 Map
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.readValue(resultMap, Map.class);
        log.info("philippineResultString is " + resultMap);
        //查到
        if (map.get("status").equals("1")) {
            List<Map<String, Object>> dataList = (List<Map<String, Object>>) map.get("data");
            for (int i = 0; i < dataList.size(); i++) {
                // 将每个 Map 对象转换为 JSON 字符串
                dataList.get(i).remove("dates");
                String jsonString = objectMapper.writeValueAsString(dataList.get(i));
                info=info+jsonString;
            }
        } else {
            //中雅接口

            paramMap.put("DanHao", DanHao);
            paramMap.put("ChannelID", ChannelID);
            paramMap.remove("card");

//            String accept = request.getHeader("Accept");
//            String userAgent = request.getHeader("User-Agent");
//
            headMap.remove("Accept");
//            headMap.put("Accept" ,accept);
            headMap.remove("User-Agent");
//            headMap.put("User-Agent" ,userAgent);
            headMap.put("Host" ,"www.pywmall.com");

            //第一次请求中雅物流首页
            String indexUrl = "http://www.zonyaa.com/index.php";
            URL indexObj = new URL(indexUrl);
            HttpURLConnection indexCon = (HttpURLConnection) indexObj.openConnection();
            indexCon.setRequestMethod("GET");
            int indexResponseCode = indexCon.getResponseCode();
            System.out.println("\n发送 'GET' 请求到 首页URL : " + indexUrl);
            System.out.println("indexResponse Code : " + indexResponseCode);
            BufferedReader indexIn = new BufferedReader(
                    new InputStreamReader(indexCon.getInputStream()));
            String indexInputLine;
            StringBuffer indexResponse = new StringBuffer();
            while ((indexInputLine = indexIn.readLine()) != null) {
                indexResponse.append(indexInputLine);
            }
            indexIn.close();
            //打印结果
            System.out.println(indexResponse.toString());

            String indexInfo = indexResponse.toString();

            log.info("indexInfo is: " + indexInfo);

            //另一种get请求写法
            String url = expressUrl + "?DanHao=" + DanHao + "&ChannelID=" + ChannelID;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            //默认值GET
            con.setRequestMethod("GET");
            //添加请求头
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Mobile Safari/537.36 Edg/127.0.0.0");
            con.setRequestProperty("Host", "www.zonyaa.com");
            con.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
//            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
            con.setRequestProperty("Proxy-Connection", "keep-alive");
            con.setRequestProperty("Referer", "http://www.zonyaa.com/index.php/Wap");
            con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            int responseCode = con.getResponseCode();
            System.out.println("\n发送 'GET' 请求到 URL : " + url);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            //打印结果
            System.out.println(response.toString());

            info = response.toString();

            //原始get请求写法
//            Map<String, Object> responseMap = HttpClientUtil.doGet(expressUrl, paramMap, headMap);
//
//            Integer responseCode = Integer.parseInt(responseMap.get("responseCode").toString());
//            String resultString = responseMap.get("resultString").toString();
//
//            log.info("User-Agent is " + headMap.get("User-Agent"));
//            log.info("responseCode is " + responseCode);
//            log.info("resultString is " + resultString);
//
//            if (!"{".equals(resultString.substring(0, 1))) {
//                //更换请求头User-Agent值并重新请求
//                headMap.remove("User-Agent");
//                headMap.remove("Accept");
//                headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");
//                headMap.put("Host" ,"www.pywmall.com");
//
//                responseMap = HttpClientUtil.doGet(expressUrl, paramMap, headMap);
//                responseCode = Integer.parseInt(responseMap.get("responseCode").toString());
//                resultString = responseMap.get("resultString").toString();
//
//                log.info("User-Agent is " + headMap.get("User-Agent"));
//                log.info("indResponseCode is " + responseCode);
//                log.info("indResultString is " + resultString);
//            }
//            try {
//                info = new JSONObject(resultString).get("info").toString();
//            } catch (JSONException e) {
//                info = "抱歉，出现未知错误，请稍后再试";
//            }


        }

        //印尼极兔
        String jntStr = "";
        JntCreateEntity jntCreateEntity = new JntCreateEntity();
        String jntResponse = jntTrackService.create(jntCreateEntity);
        List<JntTrackResponseVo> jnttrack = jntTrackService.jnttrack(jntResponse);
        for (JntTrackResponseVo responseVo : jnttrack) {
            jntStr += (responseVo.getDate_time() + "\t" + responseVo.getCity_name() + "\t" + responseVo.getStatus());
        }

        String result = detailed + info + jntStr;


        return AjaxResult.success(result);
    }

    @PostMapping("/uploadPayment")
    public AjaxResult uploadPayment(MultipartFile file ,String deliveryId){
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            //存入物流订单
            deliveryService.uploadPaymentUrl(url ,deliveryId);

            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
      *methood: 根据邮编和街道查询价格
      *auth: cyx
      *time: 2024/8/30 9:47
    **/
    @PostMapping("/selectPrice")
    public AjaxResult selectPrice(@RequestBody Map<String ,String> paramMap) {
        ExpressPriceEntity expressPriceEntity = expressPriceService.selectPrice(paramMap);
        return AjaxResult.success(expressPriceEntity);
    }

    @GetMapping("/selectExpressTree")
    public AjaxResult selectExpressTree(){
        List<ProvinceEntity> provinceEntityList = expressPriceService.selectExpressTree();
        return AjaxResult.success(provinceEntityList);
    }

    @GetMapping("/reInsert")
    public void reInsert(){
        expressService.insertTable();
    }

    /**
      *methood: 根据单号查快递
      *auth: cyx
      *time: 2024/11/30 14:57
    **/
    @GetMapping("/listByNumber")
    public AjaxResult listByNumber(String orderNumber) {
        List<DeliveryEntity> deliveryList = deliveryService.listByOrderNumber(orderNumber);
        return AjaxResult.success(deliveryList);
    }

    /**
     *methood: 确认收货
     *auth: cyx
     *time: 2024/11/30 16:49
     **/
    @PostMapping("/receive")
    public AjaxResult receive(@RequestBody Map<String ,String> paramMap) {
        String orderId = paramMap.get("orderId");
        Long userId = SecurityUtils.getUserId();
//        Long userId = 112L;
        Map data = deliveryService.receive(orderId, userId);
        String result = (String) data.get("result");
        if ("签到成功".equals(result)) {
            return AjaxResult.success(data);
        } else {
            // 使用具体的错误信息
            return AjaxResult.error(result);
        }
    }

    /**
      *methood: 根据包裹id查订单及包裹信息
      *auth: cyx
      *time: 2024/12/6 14:07
    **/
    @GetMapping("/detailByPackageId")
    public AjaxResult detailByPackageId(String packageId) {
        DeliveryEntity result = deliveryService.selectOrderByPackageId(packageId);
        return AjaxResult.success(result);
    }

    /**
      *methood: 扫码出入库
      *auth: cyx
      *time: 2024/12/6 19:42
    **/
    @PostMapping("/scanInOrOut")
    public AjaxResult scanInOrOut(@RequestBody Map<String ,String> paramMap) {
        String packageId = paramMap.get("packageId");
        String type = paramMap.get("type");
        return deliveryService.inOrOutByScan(packageId ,type);
    }
}
